import React, { PureComponent } from 'react';
import { Row, Col, Slider, Input } from 'antd';
import random from '@/utils/random';

const minValue = 10;
const maxValue = 30;
const defaultState = {
  visible: false,
  value: '',
  length: 10,
};

class SecretInput extends PureComponent {
  state = { ...defaultState };

  componentWillMount() {
    const { props } = this;
    if (props.value) {
      this.setState({ value: props.value });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { props } = this;
    if (props.value !== nextProps.value && !nextProps.value) {
      this.setState({ ...defaultState });
    } else {
      this.setState({ value: nextProps.value });
    }
  }

  handleCreatePwd = () => {
    const { length } = this.state;
    this.setState({ visible: true });
    this.handleChangeLength(length);
  };

  handleChangeLength = length => {
    const value = random.generate(length);
    this.setState({ length });
    this.handleChangeValue(value);
  };

  handleChangeValue = value => {
    const { onChange } = this.props;
    this.setState({ value });
    if (onChange) onChange(value);
  };

  render() {
    const { visible, value, length } = this.state;
    return (
      <div>
        <Row gutter={8}>
          <Col span={20}>
            <Input
              value={value}
              onChange={e => {
                this.handleChangeValue(e.target.value);
              }}
            />
          </Col>
          <Col span={4}>
            <a onClick={this.handleCreatePwd}>随机生成</a>
          </Col>
        </Row>
        {visible ? (
          <Row>
            <Col span={20}>
              <Slider
                min={minValue}
                max={maxValue}
                value={length}
                onChange={this.handleChangeLength}
              />
            </Col>
          </Row>
        ) : null}
      </div>
    );
  }
}

export default SecretInput;
